package cn.icast.netty.c5;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
@Slf4j
public class TCPServer {
    public static void main(String[] args) {

        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                       protected void initChannel(SocketChannel ch) throws Exception {

                       // ch.pipeline().addLast(new StringDecoder());

                         ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                             @Override
                             public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                 ByteBuf buf = msg instanceof ByteBuf ? (ByteBuf) msg : null;

                                 String name = buf.toString(Charset.defaultCharset());
                                 System.out.println(name);

                                 super.channelRead(ctx, msg);


                             }

                         });
                         ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                             @Override
                             public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                 System.out.println(msg+"msg");
                                 ByteBuf buffer = ctx.alloc().buffer();
                                 buffer.clear();
                                 buffer.writeBytes("hello,I am server".getBytes());

                                 ctx.writeAndFlush(buffer);
                                 buffer.release();

                             }
                         });


                    }


                }).bind(8080);

    }
}
